//
//  CSGXCommodityPickerController.m
//

#import "CSGXCommodityPickerController.h"

#import "CSGXInventoryCheckInfoView.h"

#import "CSUserDefaultsTool.h"
#import "CSGXBaseTableView.h"
#import "GXBaseTableViewCell.h"
#import "CSGXCommPreviewCell.h"

#import "TCommodityCategoryDAL.h"
#import "TCommodityInfoDAL.h"
#import "TSaleInfoDAL.h"
#import "TOrderInfoDAL.h"

#import "TOrderInfoModel.h"

static NSString * cellId = @"cellId";

@interface CSGXCommodityPickerController () <UITableViewDelegate, UITableViewDataSource>

/// 商品的大分类
@property(nonatomic,weak) CSGXBaseTableView * tvBigCatetory;
/// 商品的小分类
@property(nonatomic,weak) CSGXBaseTableView * tvSmallCategory;
/// 商品名称tv视图
@property(nonatomic,weak) CSGXBaseTableView * tvCommodity;
/// 商品详情view视图
@property(nonatomic,weak) CSGXCommInfoView * vwCommodityInfo;
@property (nonatomic, weak) CSGXInventoryCheckInfoView *vInvCheInfo;

/// 商品编辑预览
@property(nonatomic,weak) CSGXBaseTableView *tvCommodityPreview;

/// 选中的 first index
@property(nonatomic, assign) NSInteger selectedFirstIndex;
@property (nonatomic, copy) NSString * selectedFirstInfo;
/// 选中的 second index
@property(nonatomic, assign) NSInteger selectedSecondIndex;
@property (nonatomic, copy) NSString * selectedSecondInfo;
/// selected third index
@property(nonatomic, assign) NSInteger selectedThirdIndex;
@property (nonatomic, copy) NSString * selectedThirdInfo;
/// selected preview index
@property(nonatomic, assign) NSInteger selectedPreviewIndex;

///selected preview index for deselected
@property (nonatomic, strong) NSIndexPath *selectedPreIndexP;


/// tvSecond 数据 (only have Second)
@property (nonatomic, strong) NSArray<TCommodityCategoryModel *> *commSecondModels;
/// tvThird 数据 (only have Third)
@property (nonatomic, strong) NSArray<TCommodityCategoryModel *> *commThirdModels;

/// currentBackSaleModel
@property (nonatomic, strong) TSaleInfoModel * currentBackSaleModel;
/// tempSaleModelList
@property (nonatomic, strong) NSMutableArray<TSaleInfoModel *> * tempSaleModelList;

@property(nonatomic, assign) NSInteger currentThirdRow;

///tvSecond 是否加载的历史数据
@property(nonatomic, assign) BOOL isSecondHistory;
/// 历史数据的 tvThird 数据源
@property (nonatomic, strong) NSArray<TSaleInfoModel *> *commHistoryThirdModels;

/// 是否通过扫码给tvThird设置数据
@property (nonatomic, assign) BOOL isScan;
/// 通过扫码获取的数据源 commScanModels
@property (nonatomic, strong) NSArray<TCommodityInfoModel *> * commScanModels;


//orderModel
@property (nonatomic, strong) TOrderInfoModel *orderCommVcModel;


@end

@implementation CSGXCommodityPickerController
@synthesize saleModelList = _saleModelList;

+ (instancetype)commodityPickerVcWithControllerEnum:(ViewControllerEnum)controllerEnum {
    id obj = [[self alloc] init];
    ((CSGXCommodityPickerController *)obj).viewControllerEnum = controllerEnum;
    return obj;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //setp 2  (setter -> setp 5)
    [self initData];
    
#pragma mark detailView callBackBlock
    // self.detailView.callBackBlock
    __weak typeof(self) weakSelf = self;
#pragma mark -ViewControllerCarSale
    if (self.viewControllerEnum == ViewControllerCarSale) {
        self.vwCommodityInfo.callbackWithSaleModel = ^(TSaleInfoModel * backSaleModel, BOOL isEdit, NSInteger backPreviewIndex) {
            //
            if (backSaleModel.sTotalMoney == 0) {
                [weakSelf.tvCommodityPreview reloadData];
                self.selectedThirdIndex = -1;
                self.selectedPreviewIndex = -1;
                
                // post: clear detail info
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearDetailInfo" object:nil];
            }
            
            // 存入属性一份
            weakSelf.currentBackSaleModel = backSaleModel;
            
            if (backPreviewIndex == -1) { // 新创建
                if (!isEdit) {
                    // 新生成
                    [weakSelf.tempSaleModelList insertObject:backSaleModel atIndex:0];
                    
                }else {
                    // 修改
                    weakSelf.tempSaleModelList[0] = backSaleModel;
                }
                
            }else { // 从预览界面编辑
                // 从预览界面编辑
                weakSelf.tempSaleModelList[backPreviewIndex] = backSaleModel;
            }
            
            //第一次生成订单（非修改），get一个新订单号
            NSString *orderNo = [TOrderInfoDAL getOrderNoStr];
#pragma mark carSale 生成订单
            // 生成订单
            self.orderCommVcModel = [TOrderInfoDAL getOrderModelWithOrderNo:orderNo saleList:self.saleModelList];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"newListAndOrderModel" object:nil userInfo:@{@"newList":weakSelf.tempSaleModelList.copy, @"orderModel":weakSelf.orderCommVcModel}];
            
            [weakSelf.tvCommodityPreview reloadData];
        }; // call back end
    }
#pragma mark -ViewControllerInventoryCheck
    else if (self.viewControllerEnum == ViewControllerInventoryCheck) {
        self.vwCommodityInfo.callbackWithInventoryModel = ^(TInventoryModel * backInventoryModel, BOOL isNotChecked) {
            //
            if (backInventoryModel == nil) {
                return;
            }
            
//            //判断盘点状态
//            TInventoryModel *originInventoryModel = [CSGXCommodityPickerBLL loadInventoryModelWithCommNo:backInventoryModel.iCoNo];
//            backInventoryModel.iIsChecked = [CSGXCommodityPickerBLL getInventoryTypeWithCountStr:backInventoryModel.iInventoryCount
//                                                                                            originCountStr:originInventoryModel.iInventoryCount
//                                                                                                    commNo:originInventoryModel.iCoNo];
            BOOL isContain = NO;
            for (int i = 0; i < self.inventoryPreviewList.count; i++) {
                if ([backInventoryModel.iCoNo isEqualToString:self.inventoryPreviewList[i].iCoNo]) { //已经包含在预览list中，修改之。
                    if (isNotChecked) {
                        self.inventoryPreviewList[i].iIsChecked = 0; //未盘点
                        [self.inventoryPreviewList removeObjectAtIndex:i];
                    }else {
                        self.inventoryPreviewList[i] = backInventoryModel;
                    }
                    isContain = YES;
                    break;
                }
            }
            if (!isContain) { //未包含在previewList中，添加之。
                NSLog(@"-----未包含在previewList中，添加之。");
                [self.inventoryPreviewList addObject:backInventoryModel];
            }
            //            NSLog(@"InventoryCheck call back - inventoryPreviewList.count：%zd", self.inventoryPreviewList.count); //Test
            [weakSelf.tvCommodityPreview reloadData];
            
        }; //call back  end
    }
}

- (void)viewWillAppear:(BOOL)animated {

}

- (void)viewDidDisappear:(BOOL)animated {
    /* 当视图隐藏的时候
     清空tvThird、 tvPreview 的数据
     全部tv reload
     tvFirst 默认选中第一项
     */
    
    [self initData];
    [self postToClearDetail];
    [self tvsReload];
}

#pragma mark - methods
- (void)tvsReload {
    [self.tvBigCatetory reloadData];
    [self.tvSmallCategory reloadData];
    [self.tvCommodity reloadData];
    [self.tvCommodityPreview reloadData];
}

- (void)postToClearDetail {
    if (self.viewControllerEnum == ViewControllerCarSale) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearDetailInfo" object:nil];
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearCheckDetailInfo" object:nil];
    }
}


#pragma mark - tableView dataSource and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // step 5 (step 5: table view data source)
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == _tvBigCatetory) {
        return self.commFirstModels.count + 1;
    }else if (tableView == _tvSmallCategory) {
        //
        if (self.isSecondHistory) {
            return 1;
        } else {
            
            return self.commSecondModels.count;
        }
    }else if (tableView == _tvCommodity) {
        //
        if (self.isScan) {
            
            return self.commScanModels.count;
        }
        
        if (self.isSecondHistory) {
            return self.commHistoryThirdModels.count;
        } else {
            return self.commThirdModels.count;
        }
    }else if (tableView == _tvCommodityPreview) {
        //
        NSInteger cellCount = 0;
        if (self.viewControllerEnum == ViewControllerCarSale) {
            cellCount = self.tempSaleModelList.count;
        }else if (self.viewControllerEnum == ViewControllerInventoryCheck) {
            cellCount = self.inventoryPreviewList.count;
        }
        return cellCount;
    }else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //
    GXBaseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.textLabel.numberOfLines = 0;
    
    cell.selectedBackgroundView = [self getBgViewForCell:cell.contentView.bounds isIndexV:NO];
    
    if (tableView == _tvBigCatetory) {
        //
        if (indexPath.row == 0) {
            cell.textLabel.text = @"历史销售";
        }else {
            cell.textLabel.text = [NSString stringWithFormat:@"%zd:%@", self.dataIndex, self.commFirstModels[indexPath.row - 1].caFirstType];
        }
        
    }else if (tableView == _tvSmallCategory) {
        //
        if (self.isSecondHistory) {
            cell.textLabel.text = @"全部（最近一月）";
        } else {
            cell.textLabel.text = [NSString stringWithFormat:@"%zd:%@", self.dataIndex, self.commSecondModels[indexPath.row].caSecondType];
        }
        
    }else if (tableView == _tvCommodity) {
        //
        if (self.isScan) {
            cell.textLabel.text = cell.textLabel.text = [NSString stringWithFormat:@"%zd:%@", self.dataIndex, self.commScanModels[indexPath.row].cName];
            return cell;
        }
        
        if (self.isSecondHistory) {
            cell.textLabel.text = [NSString stringWithFormat:@"%zd:%@", self.dataIndex, self.commHistoryThirdModels[indexPath.row].sName];
        } else {
            cell.textLabel.text = [NSString stringWithFormat:@"%zd:%@", self.dataIndex, self.commThirdModels[indexPath.row].caThirdType];
        }
        
    }else if (tableView == _tvCommodityPreview) {
        cell.selectedBackgroundView = [self getBgViewForCell:cell.contentView.bounds isIndexV:YES];
        ((CSGXCommPreviewCell *)cell).controllerEnum = self.viewControllerEnum;
        if (self.viewControllerEnum == ViewControllerCarSale) {
            ((CSGXCommPreviewCell *)cell).dataPreviewDict = @{@"rowIndex":@(indexPath.row), @"previewModel":self.tempSaleModelList[indexPath.row]};
        }else if (self.viewControllerEnum == ViewControllerInventoryCheck) {
            ((CSGXCommPreviewCell *)cell).dataPreviewDict = @{@"rowIndex":@(indexPath.row), @"previewModel":self.inventoryPreviewList[indexPath.row]};
        }
        
    }
    
    return cell;
}

/// didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //    NSLog(@"didSelectRowAtIndexPath: %zd, %zd", indexPath.section, indexPath.row);
    
    // step 7
    if (tableView == _tvBigCatetory) {
        // first tv
        // post: clear detail info
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearDetailInfo" object:nil];
        
        [self postToClearDetail];
        
        self.selectedThirdIndex = -1;
        self.selectedPreviewIndex = -1;
        
        //load data for second tv.
        if (indexPath.row == 0) {
            self.isSecondHistory = YES;
        }else {
            
            self.selectedFirstIndex = indexPath.row - 1;
            self.selectedFirstInfo = self.commFirstModels[_selectedFirstIndex].caFirstType;
            
            self.isSecondHistory = NO;
            self.commSecondModels = [TCommodityCategoryDAL loadCoCategoryModelSecondWithFirst:self.selectedFirstInfo warehouseNo:self.warehouseNo];
            
            if (self.commSecondModels.count == 0) {
                NSLog(@"ERROR: self.commSecondModels.count == 0");
                return;
            }
        }
        
        // second tv reload
        [self.tvSmallCategory reloadData];
        
        NSIndexPath * smallIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tvSmallCategory selectRowAtIndexPath:smallIndexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        [self tableView:self.tvSmallCategory didSelectRowAtIndexPath:smallIndexPath];
        
    }else if (tableView == _tvSmallCategory) {
        // second tv
        self.selectedSecondIndex = indexPath.row;
        self.selectedThirdIndex = -1;
        self.selectedPreviewIndex = -1;
        self.isScan = NO;
        self.commScanModels = [NSArray<TCommodityInfoModel *> array];
        
        if (self.isSecondHistory) {
            //
            [self loadSecondHistory];
        } else {
            //
            self.selectedSecondInfo = self.commSecondModels[indexPath.row].caSecondType;
            self.commThirdModels = [TCommodityCategoryDAL loadCoCategoryModelThirdWithSecond:self.selectedSecondInfo warehouseNo:self.warehouseNo];
        }
        
        // post: clear detail info
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearDetailInfo" object:nil];
        [self postToClearDetail];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tvCommodity reloadData];
        });
        
    }else if (tableView == _tvCommodity) {
        // third tv
        self.selectedPreviewIndex = -1; //将tvPreview的选中cell初始化为-1。
        if (self.selectedThirdIndex == indexPath.row) {
            return;
        }
        // post: clear detail info
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearDetailInfo" object:nil];
        [self postToClearDetail];
        [self.tvCommodityPreview deselectRowAtIndexPath:_selectedPreIndexP animated:NO];
        
        if (!self.isScan) {
            // send a notification to move offsetX.
            [[NSNotificationCenter defaultCenter] postNotificationName:@"tvCommodityCellAction" object:nil userInfo:nil];
        }
        
        // Load data for detail tv based on the selected name at three tv`s.
        NSString * commCategoryStr = @"";
        
        if (self.isScan) {
            // scan
            commCategoryStr = self.commScanModels[indexPath.row].cCategory;
        }else {
            
            // isSecondHistory
            if (self.isSecondHistory) {
                //
                commCategoryStr = self.commHistoryThirdModels[indexPath.row].sCategory;
            } else {
                //
                self.selectedThirdIndex = indexPath.row;
                self.selectedThirdInfo = self.commThirdModels[indexPath.row].caThirdType;
                
                // commCategoryStr
                if (self.selectedFirstInfo && !self.selectedFirstInfo.isEmpty) {
                    commCategoryStr = [commCategoryStr stringByAppendingFormat:@"%@,", self.selectedFirstInfo];
                }
                if (self.selectedSecondInfo && ![self.selectedSecondInfo isEmpty]) {
                    commCategoryStr = [commCategoryStr stringByAppendingFormat:@"%@,", self.selectedSecondInfo];
                }
                if (self.selectedThirdInfo && !self.selectedThirdInfo.isEmpty) {
                    commCategoryStr = [commCategoryStr stringByAppendingString:self.selectedThirdInfo];
                }
            }
        } // not scan  end
        
        if (commCategoryStr.isEmpty) {
            NSLog(@"commCategoryStr 为空，请检查！");
            return;
        }
        self.vwCommodityInfo.viewControllerEnum = self.viewControllerEnum;
        self.vwCommodityInfo.commodityCategory = commCategoryStr; //@"食品,金锣,金锣王10*50g"
        self.vwCommodityInfo.isPreview = NO;
        self.vwCommodityInfo.selectedThirdIndex = indexPath.row;
        
    }else if (tableView == _tvCommodityPreview) {
        // preview tv
        // post: clear detail info
        [self postToClearDetail];
        
        if (self.selectedThirdIndex != -1) {
            [self.tvCommodity deselectRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedThirdIndex inSection:0] animated:NO];
            self.selectedThirdIndex = -1; //将tvThird的选中cell索引初始化为-1。
        }
        
        self.selectedPreviewIndex = indexPath.row;
        self.selectedPreIndexP = indexPath;
        
        // 从tempSaleModelList 中取出值显示到vwCommodityView上
        self.vwCommodityInfo.isPreview = YES;
        self.vwCommodityInfo.selectedPreviewIndex = self.selectedPreviewIndex;
        
#pragma mark ViewControllerCarSale
        if (self.viewControllerEnum == ViewControllerCarSale) {
            
            self.vwCommodityInfo.previewSaleModel = self.tempSaleModelList.copy[indexPath.row];
        }
#pragma mark ViewControllerInventoryCheck
        else if (self.viewControllerEnum == ViewControllerInventoryCheck) {
            
            self.vwCommodityInfo.inventoryModel = self.inventoryPreviewList.copy[indexPath.row];
        }
    }
}


#pragma mark - setupUI
/// cell选中的 bgView
- (UIView *)getBgViewForCell:(CGRect)frame isIndexV:(BOOL)isIndexV {
    UIView *bgvCell = [[UIView alloc] initWithFrame:frame];
    bgvCell.backgroundColor = kColorButton;
    
    if (isIndexV) {
        //lblIndex
        UILabel *lblIndex = [UILabel gx_labelWithText:@"" fontSize:12 color:[UIColor whiteColor]];
        [bgvCell addSubview:lblIndex];
        [bgvCell bringSubviewToFront:lblIndex];
        
        lblIndex.backgroundColor = [UIColor orangeColor];
        
        [lblIndex mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(bgvCell);
            make.leading.equalTo(bgvCell).offset(5);
            make.size.mas_offset(CGSizeMake(18, 15));
        }];
    }
    
    return bgvCell;
}

- (void)setupUI {
    
    self.view.backgroundColor = [UIColor grayColor];
    
    // create four tableViews and a commodityInfoView.
    
    NSMutableArray<UITableView *> *tvs = [NSMutableArray array];
    
    // tvBigCatetory
    CSGXBaseTableView * tvBigCatetory = [[CSGXBaseTableView alloc] init];
    [self.view addSubview:tvBigCatetory];
    [tvs addObject:tvBigCatetory];
    
    [tvBigCatetory registerClass:[GXBaseTableViewCell class] forCellReuseIdentifier:cellId];
    //tvBigCatetory.backgroundColor = [UIColor redColor];
    
    // tvSmallCategory
    CSGXBaseTableView * tvSmallCategory = [[CSGXBaseTableView alloc] init];
    [self.view addSubview:tvSmallCategory];
    [tvs addObject:tvSmallCategory];
    
    [tvSmallCategory registerClass:[GXBaseTableViewCell class] forCellReuseIdentifier:cellId];
    //    tvSmallCategory.backgroundColor = [UIColor magentaColor];
    
    // tvCommodity
    CSGXBaseTableView * tvCommodity = [[CSGXBaseTableView alloc] init];
    [self.view addSubview:tvCommodity];
    [tvs addObject:tvCommodity];
    
    [tvCommodity registerClass:[GXBaseTableViewCell class] forCellReuseIdentifier:cellId];
    //    tvCommodity.backgroundColor = [UIColor orangeColor];
    
    // vwCommodityInfo
    //    if (self.vcType == vcTypeCarSale) {
    //
    CSGXCommInfoView * vwCommodityInfo = [CSGXCommInfoView commInfoViewWithControllerEnum:self.viewControllerEnum];
    [self.view addSubview:vwCommodityInfo];
    self.vwCommodityInfo = vwCommodityInfo;
    
    [vwCommodityInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.top.equalTo(tvCommodity);
        make.leading.equalTo(tvCommodity.mas_trailing).offset(1);
    }];

    // tvCommodityPreview
    CSGXBaseTableView * tvCommodityPreview = [[CSGXBaseTableView alloc] init];
    [self.view addSubview:tvCommodityPreview];
    
    [tvs addObject:tvCommodityPreview];
    
    [tvCommodityPreview registerClass:[CSGXCommPreviewCell class] forCellReuseIdentifier:cellId];
    //    tvCommodityPreview.backgroundColor = [UIColor grayColor];
    
    tvCommodityPreview.estimatedRowHeight = 80;
    tvCommodityPreview.rowHeight = UITableViewAutomaticDimension;
    
    [tvCommodityPreview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.top.equalTo(tvBigCatetory);
        make.leading.equalTo(self.vwCommodityInfo.mas_trailing).offset(1);
    }];
    
    // layout
    [tvBigCatetory mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.equalTo(self.view);
        make.width.mas_equalTo(self.view).multipliedBy(1/5.0f);
    }];
    
    [tvSmallCategory mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.top.equalTo(tvBigCatetory);
        make.leading.equalTo(tvBigCatetory.mas_trailing).offset(1);
    }];
    
    [tvCommodity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.top.equalTo(tvSmallCategory);
        make.leading.equalTo(tvSmallCategory.mas_trailing).offset(1);
    }];
    
    for (UITableView * tv in tvs) {
        tv.dataSource = self;
        tv.delegate = self;
    }
    
    //
    self.tvBigCatetory = tvBigCatetory;
    self.tvSmallCategory = tvSmallCategory;
    self.tvCommodity = tvCommodity;
    self.tvCommodityPreview = tvCommodityPreview;
}

#pragma mark - loadData
- (void)loadData {
    
}

- (void)loadSecondHistory {
    
    self.commHistoryThirdModels = [TSaleInfoDAL loadListWithUserNo:[CSUserDefaultsTool getUserNo] businessNo:[CSUserDefaultsTool getBusinessmanNo] daysBefore:30];
}

- (void)initData {
#pragma mark init data
    
    // 根据 dataIndex 加载对应数据
    self.selectedFirstIndex = self.selectedSecondIndex = 0;
    self.selectedThirdIndex = -1;
    self.selectedPreviewIndex = -1;
    
    self.isScan = NO;
    
    self.currentBackSaleModel = [[TSaleInfoModel alloc] init];
    
    // 从编辑界面跳回的数据 初始化数组
    self.saleModelList = [NSArray<TSaleInfoModel *> array];
    // tvSecond data (only have Second)
    self.commSecondModels = [NSArray<TCommodityCategoryModel *> array];
    // tvThird 数据 (only have Third)
    self.commThirdModels = [NSArray<TCommodityCategoryModel *> array];
    // tvPreview
    self.tempSaleModelList = [NSMutableArray<TSaleInfoModel *> array];
    
    
#pragma mark check
    self.inventoryList = [NSArray<TInventoryModel *> array];
    self.inventoryPreviewList = [NSMutableArray<TInventoryModel *> array];
}

#pragma mark - setter & getter
#pragma mark Enter from scan
///通过扫码获得的商品编号
- (void)setCommodityNo:(NSString *)commodityNo {
    _commodityNo = commodityNo;
    self.isScan = YES;
    
    // search commoditys from tCommodityInfo based on the backObjectKey and display on the tvThird.
    TCommodityInfoModel * commModel = [TCommodityInfoDAL loadModelWithCommNo:commodityNo];
    if (!commModel) {
        UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:@"商品扫描" message:@"未找到商品，请重试！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            // 取消
        }];
        [alertVc addAction:actionCancel];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:alertVc animated:YES completion:nil];
        });
        
        
        NSLog(@"scan：没有发现此商品，请检查数据库！");
        return;
    }
    self.commScanModels = @[commModel];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tvCommodity reloadData];
    });
}

- (void)setDataIndex:(NSInteger)dataIndex {
    _dataIndex = dataIndex;
    
    // reload all tvs except preview tv.
    [self tvsReload];
    
    self.vwCommodityInfo.commodityCategory = nil; // 清空数据
}

- (void)setSaleModelList:(NSArray<TSaleInfoModel *> *)saleModelList {
    _saleModelList = saleModelList;
    
    if (!saleModelList) {
        NSLog(@"Error: saleModelList is nil!");
        return;
    }
    
    if (saleModelList.count == 0) {
        //        NSLog(@"saleModelList count = 0   --return (not error)");
        return;
    }
    
    [self.tempSaleModelList removeAllObjects];
    for (TSaleInfoModel * model in saleModelList) {
        [self.tempSaleModelList addObject:model];
    }
    
    [self.tvCommodityPreview reloadData];
}

- (NSArray<TSaleInfoModel *> *)saleModelList {
    if (!_saleModelList) {
        _saleModelList = [[NSArray<TSaleInfoModel *> alloc] init];
    }
    _saleModelList = self.tempSaleModelList;
    return _saleModelList;
}

#pragma mark Enter from homeVc
/// tvFirst model
- (void)setCommFirstModels:(NSArray<TCommodityCategoryModel *> *)commFirstModels {
    // step 4
    //set tvFirst data
    _commFirstModels = commFirstModels;
    
    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        // step 6
        if (weakSelf.commFirstModels.count == 0) {
            return;
        }
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [weakSelf.tvBigCatetory selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        
        [weakSelf tableView:weakSelf.tvBigCatetory didSelectRowAtIndexPath:indexPath];
    });
}

- (NSString *)warehouseNo {
    if (!_warehouseNo) {
        _warehouseNo = [CSUserDefaultsTool getWarehouseNo];
    }
    return _warehouseNo;
}

- (void)setInventoryPreviewList:(NSMutableArray<TInventoryModel *> *)inventoryPreviewList {
    _inventoryPreviewList = [NSMutableArray<TInventoryModel *> arrayWithArray:inventoryPreviewList];
    [self.tvCommodityPreview reloadData];
}

















@end
